<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 第一排 -->
      <el-row :gutter="20">
        <el-col  :xs="24" :sm="12" :lg="6">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col  :xs="24" :sm="12" :lg="6">
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              placeholder="请输入昵称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="6">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
              <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="6">
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col  :xs="24" :sm="12" :lg="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="" clearable>
              <el-option
                v-for="dict in status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="6">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['userInfo:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['userInfo:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['userInfo:user:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['userInfo:user:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" @sort-change="changeTableSort">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" sortable="custom" v-if="columns[0].visible" prop="name" />
      <el-table-column label="昵称" align="center" sortable="custom" v-if="columns[1].visible" prop="nickname" />
      <el-table-column label="分组" align="center" sortable="custom" v-if="columns[2].visible" prop="groups" />
      <el-table-column label="性别" align="center" sortable="custom" v-if="columns[3].visible" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" sortable="custom" v-if="columns[4].visible" prop="mobile" />
      <el-table-column label="年龄" align="center" sortable="custom" v-if="columns[5].visible" prop="age" />
      <el-table-column label="实名" align="center" sortable="custom" v-if="columns[6].visible" prop="isReal">
        <template #default="scope">
          <dict-tag :options="sys_yes_nos" :value="scope.row.isReal"/>
        </template>
      </el-table-column>
      <el-table-column label="驾驶证" align="center" sortable="custom" v-if="columns[7].visible" prop="isDriving">
        <template #default="scope">
          <dict-tag :options="sys_yes_nos" :value="scope.row.isDriving"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" sortable="custom" v-if="columns[8].visible" prop="lastlogintime">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看" placement="top">
            <el-button link type="primary" icon="View" @click="lookUserInfo(scope.row)" v-hasPermi="['userInfo:license:query']"></el-button>
          </el-tooltip>
          <el-tooltip content="发券" placement="top">
            <el-button link type="primary" icon="Ticket" @click="sendCoupon(scope.row)" v-hasPermi="['userInfo:coupon:query']"></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['userInfo:user:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['userInfo:user:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员管理对话框 -->
    <el-dialog :title="title" v-model="open" width="50vw" append-to-body :close-on-click-modal="false">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="分组">
          <el-select v-model="form.gender" placeholder="1=门店管理,2=普通用户">
            <el-option label="门店管理" :value="1"></el-option>
            <el-option label="普通用户" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <!-- <el-input v-model="form.avatar" placeholder="请输入头像" /> -->
          <imageUpload :modelValue="form.avatar" :isShowTip="false"></imageUpload>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别:0=未知,1=男,2=女">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="签名" prop="motto">
          <el-input v-model="form.motto" placeholder="请输入签名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
          <!-- <div>
            <el-radio v-model="form.status" :label="0" border>禁用</el-radio>
            <el-radio v-model="form.status" :label="1" border>启用</el-radio>
          </div> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看驾驶证弹窗 -->
    <el-dialog title="驾驶证详情" v-model="Jszopen" width="50vw" append-to-body :close-on-click-modal="false">
      <el-form :model="JszForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="JszForm.name" disabled placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="JszForm.sex" disabled placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="国籍">
          <el-input v-model="JszForm.nationality" disabled placeholder="请输入国籍" />
        </el-form-item>
        <el-form-item label="住址">
          <el-input v-model="JszForm.address" disabled placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker clearable
            v-model="JszForm.dateOfBirth"
            disabled
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="初次领证日期">
          <el-date-picker clearable
            v-model="JszForm.dateOfFirstIssue"
            disabled
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择初次领证日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="准驾车型">
          <el-input v-model="JszForm.classs" disabled placeholder="请输入准驾车型" />
        </el-form-item>
        <el-form-item label="有效期开始时间">
          <el-date-picker clearable
            v-model="JszForm.startDate"
            type="date"
            disabled
            value-format="YYYY-MM-DD"
            placeholder="请选择有效期开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期结束时间">
          <el-date-picker clearable
            v-model="JszForm.endDate"
            type="date"
            disabled
            value-format="YYYY-MM-DD"
            placeholder="请选择有效期结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="证号">
          <el-input v-model="JszForm.cardCode" disabled placeholder="请输入证号" />
        </el-form-item>
        <el-form-item label="发证单位">
          <el-input v-model="JszForm.issuingAuthority" disabled placeholder="请输入发证单位" />
        </el-form-item>
        <el-form-item label="行驶证照片">
          <ImagePreview :src="JszForm.image" :isShowTip="false" :width=" JszForm.image ? '200px' : '0px'"></ImagePreview>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="JszCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发券弹窗 -->
    <el-dialog title="发放优惠券" v-model="couponopen" width="50vw" append-to-body :close-on-click-modal="false">
      <el-form :model="couponForm" label-width="120px">
        <el-form-item label="优惠券">
          <inputsearch :changeValue="changeValue" :inputName="'id'" :inputValue="form.couponId" :list="couponList"></inputsearch>
        </el-form-item>
        <el-form-item label="优惠券数量">
          <el-input v-model="couponForm.count" type="number" placeholder="请输入优惠券数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCouponForm">保 存</el-button>
          <el-button @click="couponCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { listUser, getUser, delUser, addUser, updateUser, sendUserCoupon } from "@/api/userInfo/group";
import { listsCoupon } from "@/api/operate/coupon";
import imageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";
import inputsearch from "@/components/inputsearch";

const { proxy } = getCurrentInstance();
const { sys_user_sex, status, sys_yes_nos } = proxy.useDict('sys_user_sex', 'status', 'sys_yes_nos' );
const userList = ref([]);
const couponList = ref([]);
const open = ref(false);            // 新增修改会员信息弹窗
const Jszopen = ref(false);         // 查看驾驶证弹窗
const couponopen = ref(false);      // 发放优惠券弹窗
const columns = ref([
  { key: 0, label: `姓名`,prop: 'name', visible: true },
  { key: 1, label: `昵称`,prop: 'nickname', visible: true },
  { key: 2, label: `分组`,prop: 'groups', visible: true },
  { key: 3, label: `性别`,prop: 'gender', visible: true },
  { key: 4, label: `手机号`,prop: 'mobile', visible: true },
  { key: 5, label: `年龄`,prop: 'age', visible: true },
  { key: 6, label: `实名`,prop: 'isReal', visible: true },
  { key: 7, label: `驾驶证`,prop: 'isDriving', visible: true },
  { key: 8, label: `状态`,prop: 'lastlogintime', visible: true }
]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  JszForm: {},
  couponForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    groupId: null,
    username: null,
    nickname: null,
    email: null,
    mobile: null,
    avatar: null,
    gender: null,
    birthday: null,
    money: null,
    score: null,
    lastlogintime: null,
    lastloginip: null,
    loginfailure: null,
    joinip: null,
    jointime: null,
    motto: null,
    password: null,
    salt: null,
    status: null,
    updatetime: null,
    createtime: null,
    openId: null,
    province: null,
    city: null,
    name: null,
    idNum: null,
    orderByColumn: null,
    isAsc: null
  },
  rules: {
    groupId: [
      { required: true, message: "分组ID不能为空", trigger: "blur" }
    ],
    nickname: [
      { required: true, message: "昵称不能为空", trigger: "blur" }
    ],
    avatar: [
      { required: true, message: "头像不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别:0=未知,1=男,2=女不能为空", trigger: "change" }
    ],
    money: [
      { required: true, message: "余额不能为空", trigger: "blur" }
    ],
    score: [
      { required: true, message: "积分不能为空", trigger: "blur" }
    ],
    loginfailure: [
      { required: true, message: "失败次数不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules, JszForm, couponForm } = toRefs(data);

/** 查询会员管理列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(response => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询优惠券管理列表 */
function getCouponList() {
  listsCoupon({
    pageNum: 1,
    pageSize: 10000
  }).then(response => {
    couponList.value = response.rows.map(e => {
      e.value = e.name
      return e
    });
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    groupId: null,
    username: null,
    nickname: null,
    email: null,
    mobile: null,
    avatar: null,
    gender: null,
    birthday: null,
    money: null,
    score: null,
    lastlogintime: null,
    lastloginip: null,
    loginfailure: null,
    joinip: null,
    jointime: null,
    motto: null,
    password: null,
    salt: null,
    status: 1,
    updatetime: null,
    createtime: null,
    openId: null,
    province: null,
    city: null,
    name: null,
    idNum: null
  };
  proxy.resetForm("userRef");
}

// 驾驶证取消按钮
function JszCancel() {
  Jszopen.value = false;
  Jszreset();
}

// 驾驶证弹窗重置
function Jszreset() {
  JszForm.value = {};
}

/** 查看按钮操作 */
function lookUserInfo(row) {
  if(row.isDriving == '1'){
    Jszreset();
    JszForm.value = row.driverLicense;
    Jszopen.value = true;
  }else{
    proxy.$modal.msgWarning("当前用户暂无驾驶证");
    return
  }
}

// 发券取消按钮
function couponCancel() {
  couponopen.value = false;
  couponreset();
}

// 发券弹窗重置
function couponreset() {
  couponForm.value = {};
}

/** 发券弹窗 */
function sendCoupon(row) {
  couponreset();
  couponForm.value = {userId :row.id};
  couponopen.value = true;
}

// 改变值
const changeValue = (request) => {
  couponForm.value = Object.assign({},{
    ...couponForm.value,
    couponId: request.id
  })
}

/** 提交发券按钮 */
function submitCouponForm() {
  if(!couponForm.value.couponId){
    proxy.$modal.msgWarning("请选择优惠券");
    return
  }
  if(!couponForm.value.count){
    proxy.$modal.msgWarning("请输入发券数量");
    return
  }
  sendUserCoupon(couponForm.value).then(response => {
    proxy.$modal.msgSuccess("发券成功");
    couponopen.value = false;
    couponreset();
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.orderByColumn = null
  queryParams.value.isAsc = null
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUser(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除会员管理编号为"' + _ids + '"的数据项？').then(function() {
    return delUser(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作111 */
function handleExport() {
  proxy.download('userInfo/user/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}

// 改变排序
function changeTableSort(e){
  if(e.order){
    queryParams.value.orderByColumn = e.prop
    queryParams.value.isAsc = e.order == 'descending' ? 'desc' : 'asc'
  }else{
    queryParams.value.orderByColumn = null
    queryParams.value.isAsc = null
  }
  handleQuery()
}

getList();
getCouponList();
</script>
